<template>
    <SysDialog :title="dialog.title" :visible="dialog.visible" :width="dialog.width" :height="dialog.height"
        @onClose="onCloseDialog" @onConfirm="onConfirmDialog">
        <template v-slot:content>
            <el-form :model="adminModel" ref="adminRef" :rules="adminRules" label-width="85px" :inline="false">
                <el-form-item label="部门" prop="department">
                    <el-tree-select v-model="adminModel.department" :data="choice.deptList" check-strictly class="pid">
                    </el-tree-select>
                </el-form-item>
                <el-form-item label="账号" prop="username">
                    <el-input v-model="adminModel.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="adminModel.password" type="password" :placeholder="pwd_info" show-password>
                    </el-input>
                </el-form-item>
                <el-form-item label="名称" prop="name">
                    <el-input v-model="adminModel.name"></el-input>
                </el-form-item>
                <el-form-item label="联系方式" prop="tel">
                    <el-input v-model="adminModel.tel"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="adminModel.email"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="role">
                    <el-select v-model="adminModel.role" class="pid" placeholder="请选择">
                        <el-option v-for="role in choice.roleList" :key="role.id" :label="role.name" :value="role.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="解锁时间" prop="date_lock">
                    <el-date-picker v-model="adminModel.date_lock" type="datetime" placeholder="请选择时间"
                        value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <el-form-item label="是否启用">
                    <el-switch v-model="adminModel.is_active" inline-prompt active-text="启用" inactive-text="禁用"
                        :width="50" />
                </el-form-item>
            </el-form>
        </template>
    </SysDialog>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted } from 'vue'

import { ElForm, ElMessage } from 'element-plus'

import SysDialog from '@/components/SysDialog.vue'
import useDialog, { DialogType } from '@/hooks/useDialog'
import useInstance from '@/hooks/useInstance'
import useAdminModel, { IAdmin, IChoice, IAdminInfo } from '@/composables/admins/useAdminsModel'
import { postAdminApi, putAdminApi } from '@/http/api/admins'
import { getDeptApi } from '@/http/api/department'
import { getRoleApi } from '@/http/api/role'
import md5 from 'js-md5'

const { dialog, onShowDialog, onCloseDialog } = useDialog()
const { global } = useInstance()
const { iAdminModel, adminRules } = useAdminModel()

// 调用父组件方法
const emit = defineEmits(['newGetAdminList'])

// 部门绑定数据
const adminModel = reactive<IAdmin>(iAdminModel())
// 部门ref属性
const adminRef = ref<InstanceType<typeof ElForm>>()
// 密码框提示信息
const pwd_info = ref()
// 部门和角色下拉框
const choice: IChoice = reactive({
    deptList: [],
    roleList: []
})
// 获取部门列表
const getDeptList = async () => {
    await getDeptApi().then(res => {
        if (res && res.code == 200) {
            choice.deptList = res.data
        }
    })
}
// 获取角色列表
const getRoleList = async () => {
    await getRoleApi().then(res => {
        if (res && res.code == 200) {
            choice.roleList = res.data
        }
    })
}
// 弹窗显示
const onShow = (dialogType: string, title: string, editData?: any) => {
    global.$resetForm(adminRef.value, adminModel, iAdminModel)
    pwd_info.value = '请输入密码'
    dialog.title = title
    dialog.width = '360px'
    dialog.height = '450px'
    onShowDialog()
    if (editData && dialogType == DialogType.EDIT) {
        adminModel.id = editData.id
        adminModel.username = editData.username
        adminModel.name = editData.name
        adminModel.tel = editData.tel
        adminModel.email = editData.email
        adminModel.is_active = editData.is_active
        adminModel.date_lock = editData.date_lock
        adminModel.role = editData.role ? editData.role.id : ''
        adminModel.department = editData.department ? String(editData.department.id) : ''
        pwd_info.value = '留空表示不更改密码'
    }
    adminModel.type = dialogType
}
// 弹窗确定
const onConfirmDialog = () => {
    adminRef.value?.validate(valid => {
        if (valid) {
            if (adminModel.type == DialogType.ADD) {
                addAdmin(adminModel)
            }
            if (adminModel.type == DialogType.EDIT) {
                editAdmin(adminModel)
            }
        }
    })
}
// 添加部门
const addAdmin = async (adminModel: IAdmin) => {
    if (adminModel.password.length < 5 || adminModel.password.length > 32) {
        ElMessage.warning('请填写5-32位密码!')
        return
    }
    let user_info: IAdminInfo = {
        username: adminModel.username,
        password: md5(adminModel.password),
        name: adminModel.name,
        tel: adminModel.tel,
        email: adminModel.email,
        is_active: adminModel.is_active,
        date_lock: adminModel.date_lock,
        role: adminModel.role,
        department: adminModel.department
    }
    await postAdminApi(user_info).then(res => {
        if (res && res.code == 201) {
            ElMessage.success('添加成功！')
            emit('newGetAdminList')
            global.$resetForm(adminRef.value, adminModel, iAdminModel)
            onCloseDialog()
        } else {
            ElMessage.error(res.msg)
        }
    })
}
// 修改部门
const editAdmin = async (adminModel: IAdmin) => {
    let user_info: IAdminInfo = {
        username: adminModel.username,
        name: adminModel.name,
        tel: adminModel.tel,
        email: adminModel.email,
        is_active: adminModel.is_active,
        date_lock: adminModel.date_lock,
        role: adminModel.role,
        department: adminModel.department
    }
    if (adminModel.password) {
        if (adminModel.password.length < 5 || adminModel.password.length > 32) {
            ElMessage.warning('请填写5-32位密码!')
            return
        }
        user_info.password = md5(adminModel.password)
    }
    await putAdminApi(adminModel.id, user_info).then(res => {
        if (res && res.code == 202) {
            ElMessage.success('修改成功！')
            emit('newGetAdminList')
            global.$resetForm(adminRef.value, adminModel, iAdminModel)
            onCloseDialog()
        } else {
            ElMessage.error(res.msg)
        }
    })
}

onMounted(() => {
    getDeptList()
    getRoleList()
})

// 暴露法方给父组件
defineExpose({ onShow })

</script>

<style scoped lang='scss'>
.pid {
    width: 100%;
}
</style>